package com.dissertation.service.impl;

import com.dissertation.pojo.Message;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 中间层， 隔离查询
 */
@Service
public class SelectService {

    @Autowired
    MongoTemplate template;

    public Message findByName( String categoryTreeName, String categoryLeafName, Class<?> clazz ) {
        Query query = Query.query( where( "categoryTreeName" ).is( categoryTreeName )
                .and( "categoryLeafName" ).is( categoryLeafName ).and( "deleted" ).is( false ) );
        List<?> list = template.find( query, clazz );
        return Message.createSuc( list );
    }

    public Message findByNameAndId( String categoryTreeName, String categoryLeafName, Class<?> clazz, String id ) {
        Query query = Query.query( where( "categoryTreeName" ).is( categoryTreeName )
                .and( "categoryLeafName" ).is( categoryLeafName ).and( "deleted" ).is( false )
                .and( "id" ).is( new ObjectId( id ) ) );
        Object list = template.findOne( query, clazz );
        return Message.createSuc( list );
    }

    public Message findByNameAndDate( String categoryTreeName, String categoryLeafName, Class<?> clazz,
                                      String begin, String end, String current ) {
        Query query ;
        if (current == null)
          query = Query.query( where( "categoryTreeName" ).is( categoryTreeName )
                .and( "categoryLeafName" ).is( categoryLeafName ).and( "deleted" ).is( false )
                .and( "date" ).lte( end ).gte( begin ));
        else
            query = Query.query(where("categoryTreeName").is(categoryTreeName)
                    .and("categoryLeafName").is(categoryLeafName).and("deleted").is(false)
                    .andOperator(where("date").lte(end).gte(begin), where("date").is(current)));
        List<?> list = template.find( query, clazz );
        return Message.createSuc( list );
    }
}
